<?php

namespace Home\Controller;
use Think\Controller;
class personCenterController extends HomeController
{
    // 个人中心主页面框架
  public function personCenter()
  {
    $user_id=$_SESSION['onethink_home']['user_id'];
    if(null == $user_id){
      $this->error('您还没有登录，请先登录！', U('User/login'));
    }
    $this->assign("user_id",$user_id);
    $this->display();
  }
  // 验证码的生成
public function myverify(){
  $config = array(
    'fontSize'    =>    30,
    'length'      =>    3,
    'useNoise'    =>    false,
    );
  $Verify = new \Think\Verify($config);
  $ver = $Verify->entry();
}
// 验证码的确定
function check_verify($code, $id = ''){
  $verify = new \Think\Verify();
   return $verify->check($code, $id);
 }


  // 用户个人中心主页{}查询详情表
  public function personIndex()
  {
    $user_detail=D("user_detail");
    $user_id=I('get.user_id');
    $map["user_id"]=["eq",$user_id];
    $list=$user_detail->where($map)->select();
    $this->assign("list",$list);
    $this->assign("user_id",$user_id);
    $this->display();
  }
  // 用户详细信息添加
  public function personInfoPlus()
  {
    $user_id=I("get.user_id");
    $user=D("user");
    $umap["user_id"]=["eq",$user_id];
    $ulist=$user->where($umap)->find();
    $this->assign("ulist",$ulist);
    $this->display();
  }
  // 用户信息的新增填写
    public function personInfoAdd()
    {
      $data=I("post.");
      $user_id=I("post.user_id");
      $array=[$data["year"],$data["month"],$data["day"]];
      $age=implode("-",$array);
      $data["age"]=strtotime($age);
      $user_detail=D("user_detail");
      $data=$user_detail->create($data);
      $data["ctime"]=time();
      $res=$user_detail->add();
      if($res){
        $this->success('个人信息添加成功',U('PersonCenter/personInfo',array('user_id'=>$user_id)));
      }else{
        $this->error('个人信息添加失败',U('PersonCenter/personInfo',array('user_id'=>$user_id)));
      }
    }
  //获取用户的详细信息，进行遍历前的修改
  public function personInfo()
  {
    // 用户表的查询
    $user_id=I('get.user_id');
    $user=D("user");
    $umap["user_id"]=["eq",$user_id];
    $ulist=$user->where($umap)->find();
    // 用户详情标的查询
    $user_detail=D("user_detail");
    $map["user_id"]=["eq",$user_id];
    $list=$user_detail->where($map)->find();
    // 查询该用户的信息，同时转换时间的格式(进行切割)
      $list["date"]=date("Y-m-d",$list["age"]);
      $array=explode("-",$list["date"]);
      $list["year"]=$array[0];
      $list["month"]=$array[1];
      $list["day"]=$array[2];
    $this->assign("ulist",$ulist);
    $this->assign("list",$list);
    $this->display();
  }
  // 用户名的ajax验证
  public function usernameCheck(){
    $username=I("get.username");
    $user=D("user");
    $map["username"]=["eq",$username];
    $list=$user->where($map)->find();
    if(null==$list){
      echo ture;
    }else{
      echo false;
    }
  }
  // 个人中心用户信息的修改
  public function changeInfo()
  {
    $user_id=I("post.user_id");
    $map["user_id"]=["eq",$user_id];
    $res = $this->check_verify(I('post.mycode'));
    if(!$res){
      $this->error('验证码错误',U('PersonCenter/personInfo',array('user_id'=>$user_id)));
    }
   // 用户主表的用户名更改
    $user=new \Home\Model\PersonCenterModel("user");
      if(!empty(I("post.password"))){
        $password1=I("post.password");
        $password2=I("post.Repassword");
        $psssword3=I("post.Newpassword");
        $info=$user->where($map)->find();
        if(md5($password1)==$info["password"]&&$psssword3==$password2){
          $info["password"]=md5($psssword3);
          $res=$user->save($info);
          if($res){
            $this->success('密码修改成功',U('personInfo',array('user_id'=>$user_id)));
          }else{
      			$this->error('密码修改失败',U('personInfo',array('user_id'=>$user_id)));
      		}
        }else{
          $this->error('密码或重复密码错误',U('personInfo',array('user_id'=>$user_id)));
        }
      }
    // 用户详情标的查询与更改
    $user_detail=new \Home\Model\PersonCenterModel("user_detail");
      $datadetail=$user_detail->where($map)->find();
      $age=array(I("post.year"),I("post.month"),I("post.day"));
      $age=implode("-",$age);
      $age=strtotime($age);
      $datadetail=I('post.');
      $datadetail["age"]=$age;
    $datadetail=$user_detail->create($datadetail);
    $dres=$user_detail->where($map)->save($datadetail);
    if($dres>=0){
			$this->success('个人信息修改成功',U('personInfo',array('user_id'=>$user_id)));
		}else{
			$this->error('个人信息修改失败',U('personInfo',array('user_id'=>$user_id)));
		}
  }
  // 个人中心配送地址簿查询
  public function personAddr()
  {
    $user_addr=new \Home\Model\PersonCenterModel("user_addr");
    $user_id=I('get.user_id');
    $map["user_id"]=["eq",$user_id];
    $list=$user_addr->where($map)->order("status desc")->select();
    $this->assign("list",$list);
    $this->assign("user_id",$user_id);
    $this->display();
  }
  // 个人中心地址设为默认地址
  public function defaultAddr()
  {
    $addr_id=I("get.addr_id");
    $user_id=I("get.user_id");
    $user_addr=new \Home\Model\PersonCenterModel("user_addr");
    // 根据user_id获取的该用户的所有地址并且将其状态转换为0；
    $map["user_id"]=["eq",$user_id];
    $udata["status"]=0;
    $ures=$user_addr->where($map)->save($udata);
    // 根据addr_id设置其状态为1
    $data["addr_id"]=$addr_id;
    $data["status"]=1;
    $dmap["addr_id"]=["eq",$addr_id] ;
    $res=$user_addr->where($dmap)->save($data);
    if($res){
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'默认地址设置成功');
		}else{
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'默认地址设置失败');
		}

  }
  // 个人中心配送地址簿的新增
  public function personAddrAdd()
  {
    $user_addr=new \Home\Model\PersonCenterModel("user_addr");
    $data=I("post.");
    $address=explode("/",$data["area"]);
    $data["province"]=$address[0];
    $data["city"]=$address[1];
    $data["country"]=$address[2];
    $map["user_id"]=$data["user_id"];
    $data=$user_addr->create($data);
    $user_id=I("post.user_id");
    $res=$user_addr->where($map)->add($data);
    if($res){
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'地址簿添加成功');
		}else{
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'地址簿添加失败');
		}
  }
  //个人中心地址簿修改的查询遍历
  public function personAddrSave()
  {
    $id=I('get.addr_id');
    $user_addr=new \Home\Model\PersonCenterModel("user_addr");
    $map["addr_id"]=["eq",$id];
    $list=$user_addr->where($map)->find();
    $this->assign("list",$list);
    $this->display();
  }
  // 修改地址簿插入到数据库
  public function personSave()
  {
    $user_addr=new \Home\Model\PersonCenterModel("user_addr");
    $data=I("post.");
    $user_id=I("post.user_id");
    $address=explode("/",$data["area"]);
    $data["province"]=$address[0];
    $data["city"]=$address[1];
    $data["country"]=$address[2];
    $map["addr_id"]=["eq",I("post.addr_id")];
    $data=$user_addr->create($data);
    $res=$user_addr->where($map)->save($data);
    if($res){
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'地址簿修改成功');
		}else{
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'地址簿修改失败');
		}
  }
  // 用户收货地址删除
  public function personAddrDelete()
  {
    $user_addr=new \Home\Model\PersonCenterModel("user_addr");
    $deleteid=I("get.addr_id");
    $user_id=I("get.user_id");
    $map["addr_id"]=["eq",$deleteid];
    $res=$user_addr->where($map)->delete();
    if($res){
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'地址删除成功');
		}else{
			$this->redirect('personCenter/personAddr',array('user_id'=>$user_id),1,'地址删除失败');
		}
  }
  // 用户个人订单列表
  public function personOrder()
  {
    // 获取user_id运用连表查询，获取订单的地址表和订单表的详细信息
    $user_id=I('get.user_id');
    $order=new \Home\Model\PersonCenterModel("order");
    $sql="select * from north_order as a join north_user_addr as b
     where a.user_id=b.user_id and a.user_id={$user_id} and a.addr_id=b.addr_id order by shop_time desc";
    $list=$order->query($sql);
    // 获取查询的数据，并统计条目数量，用于分页
    $count = count($list);
    $pagenum = ceil($count / 10);
    $per = 10;
    $Page = new \Common\Controller\Page($count,$per);
    // 链表查询订单表和地址表
    $sql="select * from north_order as a join north_user_addr as b
     where a.user_id=b.user_id and a.user_id={$user_id} and a.addr_id=b.addr_id order by shop_time desc " . $Page->limit;
    $list=$order->query($sql);
    // 分页的需求参数，可以根据要求选取
    $show = $Page -> fpage($display = array(2, 3, 4, 5, 6, 7, 8));
    //在遍历事前处理数据
    $orderlist= ['未付款','已取消','未发货','已发货','未评价','已评价','申请退货','退货完成','拒绝退单'];
    foreach ($list as $key => &$val) {
      $val["order_status"]=$orderlist[$val["order_status"]];
      $val["shop_time"]=date("Y-m-d H:i:s",$val["shop_time"]);
    }
    $this->assign("list",$list);
    $this->assign("show",$show);
    $this->display();
  }

  // 订单详情列表
  public function personOrderDetail()
  {
    // 查询订单表详情
    $order_id   = I("get.order_id");
    $order_num  = I("get.order_num");
    $addr_id    = I("get.addr_id");
    $list       = D('order')->alias('a')
                  ->join('north_order_detail b ON a.order_num=b.order_num')
                  ->join('north_image c ON b.goods_id=c.goods_id')
                  ->join('north_user_addr d ON a.addr_id=d.addr_id')
                  ->where("a.order_num='$order_num'")
                  ->limit(1)->select();
    $statuslist= ['未付款','已取消','未发货','已发货','未评价','已评价','申请退货','退货完成','拒绝退单'];
    foreach($list as &$val){
      $val['image_path']    = ltrim($val['path'],'.').$val['name'];
      $val['order_status']  = $statuslist[$val['order_status']];
      $val['shop_time']     = date("Y-m-d H:i:s",$val['shop_time']);
      $val['address']       = $val['province'].$val['city'].$val['country'].$val['addr_detail'];
    }
    $this->assign("list",$list);
    $this->display();
  }

  // 订单取消操作
  public function orderCancel()
  {
    $order_id = I('get.order_id');
    $user_id  = I('get.user_id');
    $order    = new \Home\Model\PersonCenterModel("order");
    $orderlist=$order->find($order_id);
      // 更改订单状态
      $orderlist['order_status']  =  1;
    // 根据$order_id 查询north_order_detail 表的goods_id和details_id
    $detail_info = D('order_detail')->where("order_id = $order_id")->field('goods_id,details_id,good_num')->find();

    $goods_id   = $detail_info['goods_id'];
    $details_id = $detail_info['details_id'];
    $good_num   = $detail_info['good_num'];

    // 查询north_attr 中原有的库存和销量
    $attr_info  = D('attr')->where("goods_id = $goods_id and details_id = $details_id")->find();

    // 将新的库存和销量更新到商品详情表north_attr
    $old_store  = $attr_info['store'];
    $old_sale   = $attr_info['sale'];

    $data['store'] = $old_store + $good_num;
    $data['sale']  = $old_sale  - $good_num;

    //事务开启
    D()->startTrans();

    $res1 = D('attr')->where("goods_id = $goods_id and details_id = $details_id")->save($data);

    // 更新订单主表 north_order 的状态为取消状态
    $res2 = $order->save($orderlist);

    // 订单取消成功后的跳转
    if($res1 && $res2){
      D()->commit();
			$this->redirect('personCenter/personOrder',array('user_id'=>$user_id),1,'订单取消成功！');
		}else{
      D()->rollback();
			$this->redirect('personCenter/personOrder',array('user_id'=>$user_id),3,'订单取消失败！');
		}
  }

  // 商品收货交易完成
  public function orderCompletion()
  {
    $order_id=I('get.order_id');
    $user_id=I('get.user_id');
    $order=new \Home\Model\PersonCenterModel("order");
    $orderlist=$order->find($order_id);
    // 将订单状态改为4
      $orderlist['order_status']=4;
    $res=$order->save($orderlist);
    // 订单取消成功后的跳转
    if($res){
			$this->redirect('personCenter/personOrder',array('user_id'=>$user_id),0);
		}else{
			$this->redirect('personCenter/personOrder',array('user_id'=>$user_id),1,'确认收货失败');
		}
  }

// 添加商品评价
  public function goodsEvaluate()
  {
    $user_id=I("get.user_id");
    $order_id=I("get.order_id");
    // 查询用户表获取用户的用户名
    $user=new \Home\Model\PersonCenterModel("user");;
    $userlist=$user->find($user_id);
    // 查询用户详情表获取商品ID和订单号
    $order_detail=new \Home\Model\PersonCenterModel("order_detail");
    $detaillist=$order_detail->find($order_id);
    $data["user_id"]=$user_id;
    $data["username"]=$userlist["username"];
    $data["order_id"]=$order_id;
    $data["goods_id"]=$detaillist["goods_id"];
    $data["order_num"]=$detaillist["order_num"];
    $data["goods_name"]=$detaillist["goods_name"];
    $this->assign('data',$data);
    $this->display();
  }
  public function evaluateAdd()
  {
    $data=I('post.');
    $user_id=I('post.user_id');
    $order_id=I("post.order_id");
    $goods_evaluate=new \Home\Model\PersonCenterModel("goods_evaluate");
    $data=$goods_evaluate->create();
    $data["addtime"]=time();
    $goodsres=$goods_evaluate->add($data);
    // 评论成功以后订单状态由未评论改为已评论
    $order=new \Home\Model\PersonCenterModel("order");
    $orderlist=$order->find($order_id);
    // 更改订单状态，改为已评价
    $orderlist['order_status']=5;
    $res=$order->save($orderlist);
    // 评论成功后的跳转
    if($res&&$goodsres){
			$this->redirect('personCenter/personOrder',array('user_id'=>$user_id),0);
		}else{
			$this->redirect('personCenter/personOrder',array('user_id'=>$user_id),1,'评论失败');
		}
  }

  // 用户积分列表
  public function personInte()
  {
    $user_id=I('get.user_id');
    $userInte=new \Home\Model\PersonCenterModel("integralion");
    $map["user_id"]=["eq",$user_id];
    $list=$userInte->where($map)->select();
    // 获取总数量
    $count = count($list);
    $pagenum = ceil($count / 10);
    $per = 10;
    $Page = new \Common\Controller\Page($count,$per);
    $sql="select * from north_integralion where user_id={$user_id} order by ctime desc " . $Page->limit;
    $list=$userInte->query($sql);
    // 分页的需求参数，可以根据要求选取
    $show = $Page -> fpage($display = array(2, 3, 4, 5, 6, 7, 8));
    foreach ($list as $key => &$val) {
      $val["ctime"]=date("Y-m-d H:i:s",$val["ctime"]);
    }
    $dlist=$userInte->where($map)->order("id desc")->find();
    $dlist["value"]=$dlist['integral']/10;
    $this->assign("show",$show);
    $this->assign("list",$list);
    $this->assign("dlist",$dlist);
    $this->display();
  }
  // 用户退货列表的遍历
  public function personReturn()
  {
    // 获取传递的ID查询会员账号
    $user_id=I('get.user_id');
    $user=new \Home\Model\PersonCenterModel("user");
    $userlist=$user->find($user_id);
    // 获取订单id查询订单详细信息
    $order_id=I('get.order_id');
    $order=new \Home\Model\PersonCenterModel("order");
    $orderlist=$order->find($order_id);
    // 根据订单id查询订单详情表的信息
    $orderDetail=new \Home\Model\PersonCenterModel("order_detail");
    $map["order_id"]=["eq",$order_id];
    $detaillist=$orderDetail->where($map)->find();
    // 分配数据
    $this->assign('userlist',$userlist);
    $this->assign('orderlist',$orderlist);
    $this->assign('detaillist',$detaillist);
    $this->display();
  }

  // 用户个人中心退单列表
  public function personReturnList()
  {
    $user_id=I('get.user_id');
    $order_return=new \Home\Model\PersonCenterModel("order_return");
    $map["user_id"]=["eq",$user_id];
    $list=$order_return->where($map)->select();
    $statuslist= ['未付款','已取消','未发货','已发货','未评价','已评价','申请退货','退货完成','拒绝退单'];
    foreach ($list as $key => &$val) {
      $val["handletime"]=date("Y-m-d H:i:s",$val["handletime"]);
      $val["order_status"]=$statuslist[$val["order_status"]];
      $val["nowtime"]=date("Y-m-d H:i:s",time());
    }
    $this->assign('list',$list);
    $this->display();
  }

  // 退单写入数据库
  public function orderReturnAdd()
  {
    $data=I('post.');
    $user_id=I('post.user_id');
    $order_num=I("post.order_num");
    $order_return=new \Home\Model\PersonCenterModel("order_return");
    $map["order_num"]=["eq",$order_num];
    $list=$order_return->where($map)->find();
    // 如果退单表中存在该订单号，则更改该退单号的订单状态和订单表的订单状态
    if(null!=$list){
      // 更改退单表的状态
      $list['order_status']=6;
      $order_return=new \Home\Model\PersonCenterModel("order_return");
      $returnres=$order_return->save($list);
      // 更改订单表中订单状态
      $order=new \Home\Model\PersonCenterModel("order");
      $orderlist=$order->where($map)->find();
      $orderlist["order_status"]=6;
      $orderres=$order->save($orderlist);
      if($returnres&&$orderres){
        $this->success('申请退货成功',U('personOrder',array('user_id'=>$user_id)));
      }else{
        $this->error('申请退货失败',U('personOrder',array('user_id'=>$user_id)));
      }
      // 如果退单表中不存在该订单号，则写入退单表，情其状态改为6，丁订单状态同时改变
    }else{
      switch ($data["myreason"]) {
        case '1':
          $data["myreason"]="我不喜欢";
          break;
        case '2':
          $data["myreason"]="买错了";
          break;
        case '3':
          $data["myreason"]="颜色或尺寸不合适";
          break;
        case '4':
          $data["myreason"]="收货时有损坏";
          break;
        case '5':
          $data["myreason"]="与商城介绍不符";
          break;
        case '6':
          $data["myreason"]="三天内未发货";
          break;
        case '7':
          $data["myreason"]="有质量问题";
          break;
        default:
          $data["myreason"]="存在其他问题，我想退货";
          break;
      }
      // 将退货原因进行拼接
      $array=[$data["myreason"],$data["elsereason"]];
      $data["reason"]=implode(",",$array);
      //  过滤传递过来的数据信息
      $order_num=$data["order_num"];
      $data["order_status"]=6;
      $order_return=new \Home\Model\PersonCenterModel("order_return");
      $data=$order_return->create($data);
      $res=$order_return->where("order_num=".$order_num)->add($data);
      // 修改订单表的订单状态将其改为申请退货状态
      $order=new \Home\Model\PersonCenterModel("order");
      $map["order_num"]=["eq",$order_num];
      $orderlist=$order->where($map)->find();
      $orderlist["order_status"]=6;
      $orderres=$order->save($orderlist);
      // 修改状态后跳转
      if($res&&$orderres){
        $this->success('申请退货成功',U('personOrder',array('user_id'=>$user_id)));
      }else{
        $this->error('申请退货失败',U('personOrder',array('user_id'=>$user_id)));
      }
    }
  }
  // 退单函数结束

}
